package fr.generali.accueilclient.gwt.client.ui.components.form.formitem.date;

import java.util.Date;

import com.google.gwt.event.logical.shared.ShowRangeEvent;
import com.google.gwt.event.logical.shared.ShowRangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.datepicker.client.CalendarModel;
import com.google.gwt.user.datepicker.client.CalendarUtil;
import com.google.gwt.user.datepicker.client.DatePicker;
import com.google.gwt.user.datepicker.client.DefaultCalendarView;

public class DatePickerWithYearSelector extends DatePicker {

    public DatePickerWithYearSelector() {
        super(new MonthAndYearSelector(), new DefaultCalendarView(), new CalendarModel());
        MonthAndYearSelector monthSelector = (MonthAndYearSelector ) this.getMonthSelector();
        monthSelector.setPicker(this);
        monthSelector.setModel(this.getModel());
        this.addShowRangeHandlerAndFire(new ShowRangeHandler<Date>() {

            @Override
            public void onShowRange(ShowRangeEvent<Date> event) {
                final Date today = today();
                Date d = getDateWithoutSecondsAndMilliseconds(event.getStart());
                while (d.before(getDateWithoutSecondsAndMilliseconds(event.getEnd()))) {
                    if (d.after(today)) {
                        DatePickerWithYearSelector.this.setTransientEnabledOnDates(false, d);
                    }
                    nextDay(d);
                }
            }

            private void nextDay(Date d) {
                CalendarUtil.addDaysToDate(d, 1);
            }

            private Date today() {
                return getDateWithoutSecondsAndMilliseconds(new Date());
            }

            private Date getDateWithoutSecondsAndMilliseconds(Date date) {
                return DateTimeFormat.getFormat("yyyyMMdd").parse(DateTimeFormat.getFormat("yyyyMMdd").format(date));
            }
        });
    }

    public void refreshComponents() {
        super.refreshAll();
    }

}
